import subprocess
from fastapi import FastAPI
from fastapi.middleware.cors import CORSMiddleware
from app.views.item_view import item_router
from app.views.upload_view import upload_router
from app.views.new_upload_view import new_upload_router
from app.views.category_view import category_router
from app.views.index_view import index_router
from scheduled_tasks.task_scheduler import start_scheduler
from fastapi.staticfiles import StaticFiles
app = FastAPI()
# 配置跨域中间件
origins = [
    "http://127.0.0.1:8000",
    # 可以添加更多允许的源
]

app.add_middleware(
    CORSMiddleware,
    allow_origins=origins,
    allow_credentials=True,
    allow_methods=["*"],
    allow_headers=["*"],
)
app.include_router(item_router)
app.include_router(upload_router)
app.include_router(new_upload_router)
app.include_router(category_router)
app.include_router(index_router)
# 启动定时任务调度器
start_scheduler()
# 挂载静态文件目录
app.mount("/uploads", StaticFiles(directory="uploads"), name="uploads")
@app.post("/pull-git-code")
def pull_git_code():
    try:
        # 执行 git reset --hard && git pull 命令
        command = 'git reset --hard && git pull 2>&1'
        result = subprocess.run(command, shell=True, capture_output=True, text=True, check=True)
        output = result.stdout
        return {"status": "success", "message": output}
    except subprocess.CalledProcessError as e:
        error = e.stderr
        return {"status": "error", "message": error}
@app.get("/")
def read_root():
    return {"message": "Welcome to the API"}
# 全局异常处理示例
@app.exception_handler(Exception)
def global_exception_handler(request, exc):
    logger.error(f"An error occurred: {str(exc)}")
    return {"error": "An unexpected error occurred"}